﻿using ImageManager.Model;
using ImageManager.MyType;
using System.ComponentModel;
using System.Reflection;

namespace ImageManager.DBAccess.AOP
{
    public class ReadonlyCheckAction<T> : IBeforeSaveAction<T> where T : BaseModel, new()
    {
        public void Handle(BeforeSaveEventArgs<T> arg)
        {
            var propList = typeof(T).GetProperties();
            foreach (var prop in propList)
            {
                var readonlyAttribute = prop.GetCustomAttribute<MyReadonlyAttribute>();
                if (readonlyAttribute == null || arg.DataInDb == null)
                {
                    continue;
                }
                var val = prop.GetValue(arg.Data);
                var val2 = prop.GetValue(arg.DataInDb);
                if (val != val2)
                {
                    arg.Cancle = true;
                    arg.Message = "只读字段不允许修改";
                    return;
                }
            }

        }
    }
}
